import 'package:baselib/utils/image_util.dart';
import 'package:baselib/utils/log_util.dart';
import 'package:baselib/utils/navigator_util.dart';
import 'package:baselib/utils/time_util.dart';
import 'package:baselib/widgets/comm_app_bar.dart';
import 'package:baselib/widgets/comm_click_widget.dart';
import 'package:baselib/widgets/comm_password_textfield.dart';
import 'package:baselib/widgets/comm_textfield.dart';
import 'package:baselib/widgets/gradient_card_view.dart';
import 'package:baselib/widgets/gradient_text_widget.dart';
import 'package:baselib/widgets/inkwell_button.dart';
import 'package:baselib/widgets/nosize_app_bar.dart';
import 'package:baselib/widgets/refresh_util.dart';
import 'package:baselib/widgets/simple_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:framelib/config/api_config.dart';
import 'package:framelib/utils/agora_sdk_util.dart';
import 'package:framelib/utils/color_util.dart';
import 'package:framelib/utils/drawable_util.dart';
import 'package:framelib/utils/nim_sdk_util.dart';
import 'package:framelib/utils/px_util.dart';
import 'package:framelib/utils/string_util.dart';
import 'package:framelib/widgets/chat_message_image_item.dart';
import 'package:framelib/widgets/comm_widget_manager.dart';
import 'package:framelib/widgets/emoji_panel.dart';
import 'package:framelib/widgets/main_gradient_button.dart';
import 'package:framelib/widgets/page_widget.dart';
import 'package:framelib/widgets/voice_grade_widget.dart';
import 'package:get/get.dart';
import 'package:module_business/module_comm/model/user_entity.dart';
import 'package:module_business/module_comm/model/user_params_model.dart';
import 'package:module_business/module_comm/viewmodel/login_email_view_model.dart';
import 'package:module_business/module_comm/viewmodel/register_info_view_model.dart';
import 'package:module_business/module_comm/viewmodel/register_select_favorite_view_model.dart';
import 'package:module_business/module_comm/viewmodel/register_view_model.dart';
import 'package:module_business/module_index/model/voice_person_entity.dart';
import 'package:module_business/module_contact/viewmodel/chat_room_view_model.dart';
import 'package:module_business/module_index/viewmodel/my_room_view_model.dart';
import 'package:nim_core/nim_core.dart';

import 'package:agora_rtc_engine/agora_rtc_engine.dart';
/**
 * 聊天室主页
 */
class ChatRoomPage extends GetWidget<ChatRoomViewModel> {
  @override
  Widget build(BuildContext context) {
    return PageWidget.build(builder: (ChatRoomViewModel model) {
      return WillPopScope(
          onWillPop: ()=>model.toRoomClose(),
          child: PageWidget.PageScaffoldWidget(
            isShowBg: false,
            isShowBgImg: true,
            isShowBgImgPath: DrawableUtil.instance.icon_chat_room_bg,
            appBar: CommAppBar(
              backgroundColor: ColorUtil.instance.color_transparent,
              leadingWidth: PxUtil.instance.screenWidth,
              leading: Container(
                padding: EdgeInsets.only(
                  left: PxUtil.instance.px_15,
                  right: PxUtil.instance.px_15,
                ),
                child: Row(
                  children: [
                    Expanded(child: Obx(()=>Text(
                      '${StringUtil.instance.Online_User} : ${model.roomYxInfo.value.onlineUserCount??0}',
                      style: TextStyle(
                        color: ColorUtil.instance.color_white,
                        fontSize: PxUtil.instance.px_19,
                      ),
                    ))),
                    InkWellButton(
                      onPressed: ()=>model.showChatRoomOper(),
                      child: Container(
                        padding: EdgeInsets.only(
                          left: PxUtil.instance.px_25,
                          right: PxUtil.instance.px_25,
                        ),
                        child: ImagesUtil.loadAssetImage(
                          DrawableUtil.instance.icon_chat_room_more,
                          width: PxUtil.instance.px_4
                        ),
                      ),
                    ),
                    InkWellButton(
                      onPressed: ()=>model.toRoomClose(),
                      child: Container(
                        padding: EdgeInsets.only(
                        ),
                        child: ImagesUtil.loadAssetImage(
                            DrawableUtil.instance.icon_chat_room_back,
                            width: PxUtil.instance.px_25
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ),
            bottomNavigationBar: AnimatedPadding(
              padding: MediaQuery.of(context).viewInsets,
              duration: Duration(milliseconds: 100),
              child: Container(
                width: PxUtil.instance.screenWidth,
                padding: EdgeInsets.only(
                  // bottom: PxUtil.instance.px_10,
                  top: PxUtil.instance.px_10,
                ),
                color: ColorUtil.instance.color_37416d,
                // color: ColorUtil.instance.color_white,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      width: PxUtil.instance.screenWidth,
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          SizedBox(width: PxUtil.instance.px_8,),
                          Expanded(
                              child: Container(
                                  height: PxUtil.instance.px_42,
                                  alignment: Alignment.centerLeft,
                                  decoration: BoxDecoration(
                                      color: ColorUtil.instance.color_495279,
                                      borderRadius:
                                      BorderRadius.circular(PxUtil.instance.px_21)),
                                  child: Row(
                                    children: [
                                      Expanded(child: TextField(
                                        style: TextStyle(
                                            color: ColorUtil.instance.color_white
                                        ),
                                        enabled: true,
                                        textAlign: TextAlign.start,
                                        maxLength: 200,
                                        maxLines: 1,
                                        textInputAction: TextInputAction.done,
                                        keyboardType: TextInputType.text,
                                        autofocus: false,
                                        controller: model.commentController,
                                        scrollController: model.commentScrollController,
                                        // onChanged: (value)=>model.onCommentChanged(value),
                                        cursorColor: ColorUtil.instance.color_white,
                                        decoration: InputDecoration(
                                            contentPadding: EdgeInsets.only(
                                              left: PxUtil.instance.px_15,
                                              right: PxUtil.instance.px_15,
                                              bottom: PxUtil.instance.px_0,
                                            ),
                                            isDense: true,
                                            counterText: "",
                                            hintText: '${StringUtil.instance.Please_Input}...',
                                            hintStyle: TextStyle(
                                                color: ColorUtil.instance.color_half_white
                                            ),
                                            focusedBorder: UnderlineInputBorder(
                                                borderSide: BorderSide(
                                                    color: ColorUtil
                                                        .instance.color_transparent,
                                                    width: 1)),
                                            enabledBorder: UnderlineInputBorder(
                                                borderSide: BorderSide(
                                                    color: ColorUtil
                                                        .instance.color_transparent,
                                                    width: 1))),
                                      ),),
                                      SizedBox(width: PxUtil.instance.px_10,),
                                      Obx(() => InkWellButton(
                                        onPressed: ()=>model.emojiSelect(),
                                        child: Container(
                                          child: ImagesUtil.loadAssetImage(
                                              DrawableUtil.instance.icon_chat_emoji,
                                              width: PxUtil.instance.px_24,
                                              color: (model.emojiSelected.value??false)?Colors.blue:Colors.white
                                          ),
                                        ),
                                      )),
                                      SizedBox(width: PxUtil.instance.px_12,),
                                      Obx(() => InkWellButton(
                                        onPressed: ()=>model.pictureSelect(),
                                        child: ImagesUtil.loadAssetImage(
                                            DrawableUtil.instance.icon_chat_room_pick_picture,
                                            color: (model.pictureSelected.value??false)?Colors.blue:Colors.white60,
                                          width: PxUtil.instance.px_24,
                                        ),
                                      )),
                                      SizedBox(width: PxUtil.instance.px_18,),
                                    ],
                                  )
                              )),
                          InkWellButton(
                            onPressed: ()=>model.sendMsg(),
                            child: Container(
                              margin: EdgeInsets.only(
                                left: PxUtil.instance.px_6,
                                right: PxUtil.instance.px_6,
                              ),
                              child: GradientCardView(
                                elevation: PxUtil.instance.px_0,
                                gradient: LinearGradient(
                                    begin: Alignment.topCenter,
                                    end: Alignment.bottomCenter,
                                    colors: [
                                      ColorUtil.instance.color_7776FF,
                                      ColorUtil.instance.color_AD2CF1,
                                    ]
                                ),
                                padding: EdgeInsets.only(
                                  left: PxUtil.instance.px_12,
                                  right: PxUtil.instance.px_12,
                                  top: PxUtil.instance.px_5,
                                  bottom: PxUtil.instance.px_5,
                                ),
                                borderRadius: BorderRadius.circular(
                                    PxUtil.instance.px_26),
                                child: Text(
                                  StringUtil.instance.Send,
                                  style: TextStyle(
                                      color: ColorUtil.instance.color_white
                                  ),
                                ),
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                    SizedBox(height: PxUtil.instance.px_10,),
                    Obx(() => AnimatedContainer(
                      duration: const Duration(milliseconds: 300),
                      height: model.isOpenButtonUi()?PxUtil.instance.px_197:PxUtil.instance.px_0,
                      child: _getPanel(model),
                    ))
                  ],
                ),
              ),
            ),
            body: Obx(() => Container(
              width: PxUtil.instance.screenWidth,
              height: PxUtil.instance.screenHeight -
                  PxUtil.instance.statusBarHeight -
                  PxUtil.instance.appBarHeight,
              padding: EdgeInsets.only(
                left: PxUtil.instance.px_12,
                right: PxUtil.instance.px_12,
              ),
              child: RefreshUtil.init(
                model.refreshController,
                    ()=>model.onRefresh(pageCur: model.page+1),
                null,
                _buildListUi(model),
                physics: ClampingScrollPhysics(),
                loadStatus: model.loadStatus,
                enablePullDown: true,
                enablePullUp: false,
                isCanMoreData: false,
                onReFreshFunction:()=>model.onRefresh(pageCur: model.page=1),
                // scrollController: model.autoController
              ),
            )),
          ),
      );
    });
  }
  Widget _getPanel(ChatRoomViewModel model) {

    if (model.emojiSelected.value??false) {
      return EmojiPanel(
        onEmojiSelected: (emoji) {
          final text = model.commentController.text;
          final textFinal =  "$text$emoji";
          model.commentController.text = textFinal;
          model.commentController.selection=TextSelection.fromPosition(TextPosition(
              affinity: TextAffinity.downstream,
              offset: textFinal.length));
        },
        onEmojiDelete: () {
          String originText = model.commentController.text;
          var text = originText.characters.skipLast(1);
          model.commentController.text = "$text";
          model.commentController.selection=TextSelection.fromPosition(TextPosition(
              affinity: TextAffinity.downstream,
              offset: model.commentController.text.length));
          // inputText = model.commentController.text;
        },
      );
    }
    return Container();
  }

  Widget _buildListUi(ChatRoomViewModel model) {
    return ListView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        itemCount: model.chatRoomMsgs.value.length??0,
        itemBuilder:(BuildContext context,int index){
          NIMChatroomMessage chatRoomMsgItem = model.chatRoomMsgs.value[index];
          if(chatRoomMsgItem.messageDirection == NIMMessageDirection.outgoing){
            //自己发出去的
            return buildSelfMsgUi(model,chatRoomMsgItem);
          }else{
            //收到的
            return buildOtherMsgUi(model,chatRoomMsgItem);
          }
        }
    );
  }

  Widget buildSelfMsgUi(ChatRoomViewModel model, NIMChatroomMessage msgDataItem) {
    UserEntity chatRoomServiceMember = UserEntity();
    var chatRoomServiceMembersTemp =
    (model.chatRoomServiceMembers??[]).where((element) => (element?.yxAccid==msgDataItem?.fromAccount)).toList();
    if(chatRoomServiceMembersTemp.isNotEmpty)chatRoomServiceMember= chatRoomServiceMembersTemp[0];
    return Container(
      width: PxUtil.instance.screenWidth,
      margin: EdgeInsets.only(
          bottom: PxUtil.instance.px_30
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: PxUtil.instance.screenWidth/4,
          ),
          Expanded(child: Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              _buildChatItemUi(model,msgDataItem),
              SizedBox(height:  PxUtil.instance.px_5,),
              Text(
                '${TimeUtils.forMatTimeByMs(msgDataItem?.timestamp,format: 'yyyy-MM-dd HH:mm:ss')}',
                style: TextStyle(
                    fontSize: PxUtil.instance.px_8,
                    color: ColorUtil.instance.color_white
                ),
              )
            ],
          )),
          InkWellButton(
            onPressed: ()=>model.onPersonTap(msgDataItem,chatRoomServiceMember),
            // onPressed: (){},
            child: Container(
                margin: EdgeInsets.only(
                    left: PxUtil.instance.px_12,
                    right: PxUtil.instance.px_12
                ),
                child:
                CommWidgetManager.buildCicleImagWidget(
                  chatRoomServiceMember?.icon?? '',
                  placeholder:
                  DrawableUtil.instance.icon_default_head,
                  width: PxUtil.instance.px_32,
                  height: PxUtil.instance.px_32,
                  roundRadius: PxUtil.instance.px_16,
                  backgroundColor: ColorUtil.instance.color_f2f2f2,
                  padding: EdgeInsets.only(),
                  margin: EdgeInsets.only(),
                )
            ),
          ),
        ],
      ),
    );
  }
  Widget buildOtherMsgUi(ChatRoomViewModel model, NIMChatroomMessage msgDataItem) {
    UserEntity chatRoomServiceMember = UserEntity();
    var chatRoomServiceMembersTemp =
    (model.chatRoomServiceMembers??[]).where((element) => (element?.yxAccid==msgDataItem?.fromAccount)).toList();
    if(chatRoomServiceMembersTemp.isNotEmpty)chatRoomServiceMember= chatRoomServiceMembersTemp[0];
    return Container(
      width: PxUtil.instance.screenWidth*3/4,
      margin: EdgeInsets.only(
          bottom: PxUtil.instance.px_30
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          InkWellButton(
            onPressed: ()=>model.onPersonTap(msgDataItem,chatRoomServiceMember),
            child: Container(
                margin: EdgeInsets.only(
                    left: PxUtil.instance.px_12,
                    right: PxUtil.instance.px_12
                ),
                child:
                CommWidgetManager.buildCicleImagWidget(
                  chatRoomServiceMember?.icon ?? '',
                  placeholder:
                  DrawableUtil.instance.icon_default_head,
                  width: PxUtil.instance.px_32,
                  height: PxUtil.instance.px_32,
                  roundRadius: PxUtil.instance.px_16,
                  backgroundColor: ColorUtil.instance.color_f2f2f2,
                  padding: EdgeInsets.only(),
                  margin: EdgeInsets.only(),
                )
            ),
          ),
          Expanded(child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildChatItemUi(model,msgDataItem),
              SizedBox(height:  PxUtil.instance.px_5,),
              Text(
                '${TimeUtils.forMatTimeByMs(msgDataItem?.timestamp,format: 'yyyy-MM-dd HH:mm:ss')}',
                style: TextStyle(
                    fontSize: PxUtil.instance.px_8,
                    color: ColorUtil.instance.color_white
                ),
              )
            ],
          )),
          SizedBox(
            width: PxUtil.instance.screenWidth/4,
          ),
        ],
      ),
    );
  }
  _buildChatItemUi(ChatRoomViewModel model, NIMChatroomMessage msgDataItem) {
    switch (msgDataItem.messageType) {
      case NIMMessageType.text:
        return Container(
          padding: EdgeInsets.only(
            left: PxUtil.instance.px_15,
            right: PxUtil.instance.px_15,
            top: PxUtil.instance.px_10,
            bottom: PxUtil.instance.px_10,
          ),
          decoration: BoxDecoration(
              color: ColorUtil.instance.color_4b5e91,
              borderRadius: BorderRadius.circular(PxUtil.instance.px_20)
          ),
          child: Text(
            '${msgDataItem?.content??''}',
            style: TextStyle(
                color: ColorUtil.instance.color_white,
                fontSize: PxUtil.instance.px_14
            ),
          ),
        );
      // case NIMMessageType.audio:
      //   return ChatMessageAudioItem(
      //     message: msgDataItem,
      //   );
      case NIMMessageType.image:
        return ChatMessageImageItem(
          message: msgDataItem,
        );
      // case NIMMessageType.video:
      //   return ChatMessageVideoItem(
      //     message: msgDataItem,
      //   );
    // case NIMMessageType.notification:
    //   if (messageItemBuilder?.notifyMessageBuilder != null) {
    //     return messageItemBuilder!.notifyMessageBuilder!(message.nimMessage);
    //   }
    //   return ChatKitMessageNotificationItem(message: message.nimMessage);
    // case NIMMessageType.tip:
    //   if (messageItemBuilder?.tipsMessageBuilder != null) {
    //     return messageItemBuilder!.tipsMessageBuilder!(message.nimMessage);
    //   }
    //   return ChatKitMessageTipsItem(message: message.nimMessage);
      default:
        return Container(
          padding: EdgeInsets.only(
            left: PxUtil.instance.px_15,
            right: PxUtil.instance.px_15,
            top: PxUtil.instance.px_10,
            bottom: PxUtil.instance.px_10,
          ),
          decoration: BoxDecoration(
              color: ColorUtil.instance.color_4b5e91,
              borderRadius: BorderRadius.circular(PxUtil.instance.px_20)
          ),
          child: Text(
            '${msgDataItem?.content??''}',
            style: TextStyle(
                color: ColorUtil.instance.color_white,
                fontSize: PxUtil.instance.px_14
            ),
          ),
        );
    }
  }
}
